package com.laikan.reader.bookfriend.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.MaterBean;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.core.utils.PublicUtil;
import com.socks.library.KLog;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 个人中心-->我的资料-->我的性别页
 * Created by Administrator on 2016/5/3.
 */
public class GenderActivity extends BasicActivity implements View.OnClickListener {

    private ImageView back_tv; //返回键
    Drawable drawable_back_tv;
    private RelativeLayout back_layout;
    private ListView listView;
    private List<SettingGender> listGender = new ArrayList<SettingGender>();
    private Bitmap redGouDrawable; //红对勾
    private SettingAdapter settingAdapter;
    private String gender; // 性别
    private TextView save; //保存
    private String gender_temp; //临时变量
    private LoadingDialog loadingDialog;

    public static final String GENDER_MALE = "1";
    public static final String GENDER_FEMALE = "2";
    public static final String GENDER_SECRET = "3";

    @Override
    public void assignViews() {
        loadingDialog = new LoadingDialog(mContext);
        setContentView(R.layout.lk_gender);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        save = (TextView)findViewById(R.id.tv_save);
        listView = (ListView)findViewById(R.id.list_view);
    }

    @Override
    public void initData() {
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        gender = getIntent().getStringExtra("gender"); //默认为保密

        redGouDrawable = PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.whitegou), Color.parseColor("#66ccdd"));
        SettingGender gender = new SettingGender();
        gender.setChoose("男");
        listGender.add(gender);
        gender = new SettingGender();
        gender.setChoose("女");
        listGender.add(gender);
        gender = new SettingGender();
        gender.setChoose("保密");
        listGender.add(gender);
        for(SettingGender sg : listGender){
            if (sg.getChoose().equals(this.gender)){
                sg.setShowed(true);
            }
        }
        settingAdapter = new SettingAdapter(getApplicationContext());
        listView.setAdapter(settingAdapter);
    }

    @Override
    public void setListener() {
        back_layout.setOnClickListener(this);
        save.setOnClickListener(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        listGender.get(0).setShowed(true);
                        listGender.get(1).setShowed(false);
                        listGender.get(2).setShowed(false);
                        gender_temp = GENDER_MALE;

                        break;
                    case 1:
                        listGender.get(0).setShowed(false);
                        listGender.get(1).setShowed(true);
                        listGender.get(2).setShowed(false);
                        gender_temp = GENDER_FEMALE;

                        break;
                    case 2:
                        listGender.get(0).setShowed(false);
                        listGender.get(1).setShowed(false);
                        listGender.get(2).setShowed(true);
                        gender_temp = GENDER_SECRET;

                        break;
                }
                settingAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_layout:
                finish();
                break;
            case R.id.tv_save:
                submit();
            default:
                break;
        }
    }

    private void submit() {
        loadingDialog.show();
        Map<String, String> map = new HashMap<String, String>();
        map.put("gender", gender_temp);
        map.put("sd", SPUtil.getString("token", ""));
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                loadingDialog.dismiss();
                BaseDataBean<MaterBean> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<MaterBean>>() {}.getType();

                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (result.getData() == null && !Constants.RESULT_OK.equals(result.getResult())) {
                            ToastMgr.showShortToast(result.getError_msg());
                        }else {
                            if (result.getData().isStatus()) {
                                ToastMgr.showShortToast(R.string.gender_modify_success);
                                Intent intent = new Intent();
                                intent.putExtra("return_gender", gender_temp);
                                setResult(RESULT_OK, intent);
                                finish();
                            }else {
                                ToastMgr.showShortToast(R.string.gender_modify_failed);
                            }
                        }
                    }else {
                        ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    }
                }catch (Exception e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                loadingDialog.dismiss();
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。30");
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_userextent_update);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    class SettingAdapter extends BaseAdapter {

        private Context mContext;
        private LayoutInflater mlayoutInflater;

        public SettingAdapter(Context context) {
            this.mContext = context;
            mlayoutInflater = LayoutInflater.from(mContext);
        }

        @Override
        public int getCount() {
            return listGender.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            ViewHolder viewHolder;
            if (convertView == null) {
                view = mlayoutInflater.inflate(R.layout.setting_gender_item, null);
                viewHolder = new ViewHolder();
                viewHolder.itemChoose = (TextView)view.findViewById(R.id.item_choose);
                viewHolder.itemImage = (ImageView)view.findViewById(R.id.item_image);
                view.setTag(viewHolder);
            }else {
                view = convertView;
                viewHolder = (ViewHolder)view.getTag();
            }
            viewHolder.itemChoose.setText(listGender.get(position).getChoose());
            if (listGender.get(position).isShowed()) {
                viewHolder.itemImage.setImageBitmap(redGouDrawable);
                viewHolder.itemImage.setVisibility(View.VISIBLE);
            }else {
                viewHolder.itemImage.setVisibility(View.GONE);
            }
            return view;
        }

        class ViewHolder {

            TextView itemChoose;
            ImageView itemImage;
        }
    }
}